package com.cloudwave.trailends.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.cloudwave.trailends.AppContext;
import com.cloudwave.trailends.Constants;
import com.cloudwave.trailends.R;
import com.cloudwave.trailends.compo.BaseActivity;
import com.cloudwave.trailends.domain.RidingLine;
import com.cloudwave.trailends.entity.ResultEntity;
import com.cloudwave.trailends.utils.StatisticsUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

/**
 * 
 * @author 龙雪
 * @date 2014年12月18日
 * 
 */

public class EditActivity extends BaseActivity {
	private static final String TAG = "EditActivity";
	
	private ImageButton btnBack;
  	private ImageButton btnOK;
  	private TextView tvTitle;
  	
  	private EditText tvLineTitle;
  	private EditText tvLineDesc;
  	
  	private RidingLine rl = null;
  	
  	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.riding_line_edit);
		
		initView();
		
		initData();
	}

	private void initView() {
		btnBack = (ImageButton) findViewById(R.id.btnBack);
		tvTitle = (TextView) findViewById(R.id.tvTitle);
		btnOK = (ImageButton) findViewById(R.id.btnOK);
		tvLineTitle = (EditText) findViewById(R.id.tvLineTitle);
		tvLineDesc = (EditText) findViewById(R.id.tvLineDesc);
		
		tvTitle.setText("编辑骑记");
		btnOK.setVisibility(View.VISIBLE);
		
		btnBack.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				saveCache();
				EditActivity.this.finish();
			}
		});

		btnOK.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				saveRidingLine();
			}
		});
	}

	private void initData() {
		Long id = getIntent().getLongExtra("rlId", 0);
		if (id == null || id == 0) {
			Toast.makeText(EditActivity.this, "参数错误~_~", Toast.LENGTH_SHORT).show();
			Log.w(TAG, "没有接收到参数!");
			this.finish() ;
		}
		
		DbUtils dbu = DbUtils.create(this, Constants.DB_NAME);
		try {
			rl = dbu.findById(RidingLine.class, id);
		} catch (DbException e) {
			Toast.makeText(EditActivity.this, "加载骑记失败~_~", Toast.LENGTH_SHORT).show();
			Log.w(TAG, "查询记录数据异常:", e);
			this.finish() ;
		}
		
		if ( rl == null ) {
			Toast.makeText(EditActivity.this, "骑记不存在或已经删除~_~", Toast.LENGTH_SHORT).show();
			this.finish() ;
		}
		
		tvLineTitle.setText(rl.getTitle());
		if ( !TextUtils.isEmpty(rl.getDescription()) ) {
			tvLineDesc.setText(rl.getDescription());
		}
	}
	
	private void saveRidingLine() {
		String title = tvLineTitle.getText().toString();
		String desc = tvLineDesc.getText().toString();
		
		if ( TextUtils.isEmpty(title) ) {
			Toast.makeText(EditActivity.this, "骑记标题不能为空哦^_^", Toast.LENGTH_SHORT).show();
			return ;
		}
		if ( rl.getRemoteId() == null ) {
			rl.setTitle(title);
			rl.setDescription(desc);
			DbUtils dbu = DbUtils.create(this, Constants.DB_NAME);
			try {
				dbu.update(rl, WhereBuilder.b("id_", "==", rl.getId()), "title_", "description_");
				
				Intent intent = new Intent();
                intent.putExtra("title", title);
                EditActivity.this.setResult(RESULT_OK, intent);
                Toast.makeText(EditActivity.this, "修改成功!", Toast.LENGTH_SHORT).show();
                exitAndSendNotice();
			} catch (DbException e) {
				Toast.makeText(EditActivity.this, "保存数据异常~_~", Toast.LENGTH_SHORT).show();
				Log.e(TAG, e.getMessage());
			}
		} else {
			RequestParams params = new RequestParams();
			StatisticsUtils.newInstance(this).appendParams("1", params);
			params.addBodyParameter("token", ((AppContext) getApplication()).getToken());
			RidingLine rlTmp = new RidingLine();
			rlTmp.setId(rl.getRemoteId());
			rlTmp.setTitle(title);
			rlTmp.setDescription(desc);
			params.addBodyParameter("entity", JSON.toJSONString(rlTmp));
			
			HttpUtils http = new HttpUtils();
			http.send(HttpRequest.HttpMethod.POST, Constants.URL_RIDINGLINE_UPDATE, params, new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					
					if (responseInfo.statusCode != 200 && TextUtils.isEmpty(responseInfo.result)) {
						Toast.makeText(EditActivity.this, "未获取到返回数据,请重试!", Toast.LENGTH_SHORT).show();
						Log.i(TAG, "未获取到返回数据!");
					} else {
						Log.i(TAG, "获取到返回数据:"+responseInfo.result);
						ResultEntity rt = JSON.parseObject(responseInfo.result, ResultEntity.class);
						if ( rt.isSuccess() ) {
							updateAndExit();
						} else {
							Toast.makeText(EditActivity.this, rt.getCodeMsg(), Toast.LENGTH_SHORT).show();
							return ;
						}
					}
				}
				@Override
				public void onFailure(HttpException error, String msg) {
					Toast.makeText(EditActivity.this, "修改失败,请检查您的网络!", Toast.LENGTH_SHORT).show();
					Log.e(TAG, error.getMessage());
				}
			});
		}
	}
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		saveCache();
		this.finish();
	}
	
	private void saveCache() {
		String title = tvLineTitle.getText().toString();
		String desc = tvLineDesc.getText().toString();
		if ( !TextUtils.isEmpty(title) ) {
			((AppContext) getApplication()).put(Constants.CACHE_RIDING_LINE_EDIT_TITLE, title);
		}
		if ( !TextUtils.isEmpty(desc) ) {
			((AppContext) getApplication()).put(Constants.CACHE_RIDING_LINE_EDIT_DESC, desc);
		}
	}
	
	private void updateAndExit() {
		String title = tvLineTitle.getText().toString();
		String desc = tvLineDesc.getText().toString();
		
		rl.setTitle(title);
		rl.setDescription(desc);
		DbUtils dbu = DbUtils.create(this, Constants.DB_NAME);
		try {
			dbu.update(rl, WhereBuilder.b("id_", "==", rl.getId()), "title_", "description_");
            exitAndSendNotice();
		} catch (DbException e) {
			Toast.makeText(EditActivity.this, "保存数据异常~_~", Toast.LENGTH_SHORT).show();
			Log.e(TAG, e.getMessage());
		}
	}
	
	private void exitAndSendNotice() {
		String title = tvLineTitle.getText().toString();
		Intent intent = new Intent();
        intent.putExtra("title", title);
        EditActivity.this.setResult(RESULT_OK, intent);
        
//		Intent intent = new Intent();
//		intent.setAction(RidingService.CTRL_CONTINUE);
//		long id = getIntent().getLongExtra("rlId", 0);
//		intent.putExtra("rlId", id);
//		sendBroadcast(intent);
//		Toast.makeText(EditActivity.this, "修改成功!", Toast.LENGTH_SHORT).show();
        
        this.finish();
	}
	
}
